import React, { useEffect, useState } from 'react'; // 添加 useEffect 和 useState
import Post from '../components/Post';
import Profile from '../components/Profile';
import { useParams } from 'react-router-dom';
import './Home.css';  // 样式文件
import { getMyPosts } from '../api/userApi'; // 导入接口

const Personal = () => {
  const { userId } = useParams(); // 从路由中获取 userId
  const [posts, setPosts] = useState([]); // 初始化状态保存帖子数据
  const [loading, setLoading] = useState(true); // 初始化加载状态
  const [error, setError] = useState(null); // 初始化错误状态

  useEffect(() => {
    const fetchPosts = async () => {
      if (!userId) return;

      const currentUserId = localStorage.getItem('userId'); // 获取当前用户 ID
      try {
        const postsData = await getMyPosts(currentUserId, userId); // 调用接口获取用户帖子
        setPosts(postsData); // 更新状态
      } catch (err) {
        setError(err.message); // 处理错误
      } finally {
        setLoading(false); // 设置加载状态完成
      }
    };

    fetchPosts(); // 调用获取数据的函数
  }, [userId]);

  if (loading) {
    return <div>加载中...</div>; // 显示加载状态
  }

  if (error) {
    return <div>错误: {error}</div>; // 显示错误信息
  }

  // 渲染博客数据
  const myProfilePosts = posts.map((blog) => ({
    userId: blog.userId,
    userImage: blog.userImage,
    blogImage: blog.blogImage,
    interestId: blog.interestId,
    blogId: blog.blogId,
    title: blog.name,
    author: blog.account,
    content: blog.description,
    time: blog.updateTime,
    likeCount: blog.likesCount,
    commentCount: blog.commentsCount,
    isLiked: blog.isLiked,
    isFollowed: blog.isFollowed,
    isCollected: blog.isCollected,
  }));

  return (
    <div className="home">
      <div className="home-left">
        <div className="home-body">
          <div className="personal-posts-section">
            {myProfilePosts.map((post) => (
              <Post key={post.blogId} post={post} /> // 使用接口获取的帖子渲染组件
            ))}
          </div>
        </div>
      </div>
      <div className="right-section">
        <Profile userId={userId} /> {/* 将 userId 作为 props 传递给 Profile 组件 */}
      </div>
    </div>
  );
};

export default Personal;
